package cn.ybz21.hibot.monitor;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.ybz21.hibot.bean.Node;
import cn.ybz21.hibot.util.shell.CmdExec;

/**
 * 
 * @author ybz
 * @email bingzheng_yan@163.com
 * @time 2017年10月12日
 */
public class NodeInfoCollect {
//	public static void main(String[] args) {
//		new NodeInfoCollect().getInfo();
//	}

	public List<Node> getInfo() {
		List<Node> nodes = getNodeList();
		for (Node node : nodes) {
			getNodeInfo(node);
			System.out.println(node);
		}
		return nodes;
	}

	/**
	 * 获取所有Node列表
	 * 
	 * @return
	 */
	private List<Node> getNodeList() {
		List<Node> nodes = new ArrayList<Node>();
		String shell = "rosnode list";
		String str = new CmdExec().execCmd4Str(shell);
		String lines[] = str.split("\n");
		for (String line : lines) {
			Node node = new Node();
			node.name = line;
			nodes.add(node);
		}
		return nodes;
	}

	/**
	 * 填充每个node的信息
	 * 
	 * @param node
	 * @return
	 */
	private Node getNodeInfo(Node node) {
		String shell = "rosnode info " + node.name;
		String str = new CmdExec().execCmd4Str(shell);
		String lines[] = str.split("\n");
		String pid = "0";
		for (String line : lines) {
			if (line.startsWith("Pid")) {
				pid = line.replace("Pid:", "");
				break;
			}
		}
		node.info = str;
		node.pid = pid;
		node = getCpuNMemory(node);
		return node;
	}

	/**
	 * 填充每个 node的cpu和memory
	 * 
	 * @param node
	 * @return
	 */
	private Node getCpuNMemory(Node node) {
		String shell = "top -b -n 1 -p " + node.pid;
		String str = new CmdExec().execCmd4Str(shell);
		String lines[] = str.split("\n");
		String line = lines[lines.length - 1];
		line = line.replace(" ", "-");
		// String strInput =
		// "-3838-ybz-------20---0--323748--11888---8952-S---0.0--0.1---0:02.06-rosout";
		String regEx = "[^0-9.]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(line);
		String string = m.replaceAll(" ").trim();
		String[] strArr = string.split(" ");
		int i = 0;
		double cpu = 0, memory = 0, temp = 0;
		for (String s : strArr) {
			try {
				temp = Double.parseDouble(s);
				i++;
				if (i == 7)
					cpu = temp;
				if (i == 8)
					memory = temp;
			} catch (Exception e) {

			}
		}
		node.cpu = cpu;
		node.memory = memory;
		return node;
	}
}
